package com.phuoc.activities;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.phuoc.dao.EstablishmentDAO;
import com.phuoc.dao.TypeOfEstablishmentDAO;
import com.phuoc.dao.TypeOfFoodDAO;
import com.phuoc.entities.Establishment;

@TargetApi(9)
public class EditEstablishActivity extends CustomWindow {

	// DAO
	private EstablishmentDAO estabDataSource;
	private TypeOfEstablishmentDAO typeEstabDataSource;
	private TypeOfFoodDAO typeFoodDataSource;

	// Adapter
	private ArrayAdapter<String> adapterForTypeOfEstab;
	private ArrayAdapter<String> adapterForTypeOfFood;

	// layout
	private EditText edtEstabId;
	private EditText edtEstabName;
	private Spinner spinTypeOfEstab;
	private Spinner spinTypeOfFood;
	private EditText edtLocation;
	private TextView txtDate;
	private TextView txtMeal;
	private TextView txtCost;
	private RatingBar rateService;
	private RatingBar rateAtmosphere;
	private RatingBar rateFood;
	private RatingBar rateOverall;
	private EditText edtComments;

	// Dialog
	private Dialog dialogRate;
	private Dialog dialogTime;
	private Dialog dialogMeal;
	private Dialog dialogCost;
	private Dialog dialogNewTypeOfEstab;
	private Dialog dialogNewTypeOfFood;
	private ProgressDialog dialogWaiting;
	private Handler handler;

	// Rating
	private RatingBar ratingEstab;

	// Data advance details
	private Establishment estab;
	private String id;
	private float serviceScore = 0;
	private float atmosphereScore = 0;
	private float foodScore = 0;
	private float overallScore = 0;
	private String date;
	private String meal;
	private float cost = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit);
		this.setWindowTitle("Edit Establishment");

		// Get id from Details Establishment
		id = getIntent().getExtras().getString("id");

		// Initial DAO
		estabDataSource = new EstablishmentDAO(this);
		estabDataSource.open();
		typeEstabDataSource = new TypeOfEstablishmentDAO(this);
		typeEstabDataSource.open();
		typeFoodDataSource = new TypeOfFoodDAO(this);
		typeFoodDataSource.open();

		// Find view
		edtEstabId = (EditText) findViewById(R.id.edtEstabId);
		edtEstabName = (EditText) findViewById(R.id.edtEstabName);
		spinTypeOfEstab = (Spinner) findViewById(R.id.spinTypeOfEstab);
		spinTypeOfFood = (Spinner) findViewById(R.id.spinTypeOfFood);
		edtLocation = (EditText) findViewById(R.id.edtEstabLocation);
		txtDate = (TextView) findViewById(R.id.txtDateView);
		txtMeal = (TextView) findViewById(R.id.txtTypeOfMeal);
		txtCost = (TextView) findViewById(R.id.txtCost);
		rateService = (RatingBar) findViewById(R.id.viewRateService);
		rateAtmosphere = (RatingBar) findViewById(R.id.viewRateAtmosphere);
		rateFood = (RatingBar) findViewById(R.id.viewRateFood);
		rateOverall = (RatingBar) findViewById(R.id.viewRateOverall);
		edtComments = (EditText) findViewById(R.id.edtComments);

		// Find dialog
		dialogRate = new Dialog(this);
		dialogRate.setContentView(R.layout.rate);
		ratingEstab = (RatingBar) dialogRate.findViewById(R.id.ratingEstab);

		dialogTime = new Dialog(this);
		dialogTime.setContentView(R.layout.time);

		dialogMeal = new Dialog(this);
		dialogMeal.setContentView(R.layout.meal);

		dialogCost = new Dialog(this);
		dialogCost.setContentView(R.layout.cost);

		dialogNewTypeOfEstab = new Dialog(this);
		dialogNewTypeOfEstab.setContentView(R.layout.new_type);

		dialogNewTypeOfFood = new Dialog(this);
		dialogNewTypeOfFood.setContentView(R.layout.new_type);

		handler = new Handler();

		// Display info to View
		displayInfo();

		// Cancel Dialog event clicked
		cancelDialogClicked();

		// Set Dialog Time event clicked
		setTime();

		// Set Meal event clicked
		selectTypeOfMeal();

		// Set Cost event clicked
		setCost();

		// Add data to spinner type of establishment
		addDataToSpinnTypeOfEstab();

		// Add data to spinner type of food
		addDataToSpinnTypeOfFood();

		// Event EditText Changed
		EventEditTextTextChanged();

		// Event Add New Type Of Establishment
		addNewTypeOfEstabEvent();

		// Event Add New Type Of Food
		addNewTypeOfFoodEvent();
	}

	@Override
	protected void onResume() {
		estabDataSource.open();
		typeEstabDataSource.open();
		typeFoodDataSource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		estabDataSource.close();
		typeEstabDataSource.close();
		typeFoodDataSource.close();
		super.onPause();
	}

	private void displayInfo() {
		// Get Establishment by Id
		estab = estabDataSource.getEstablishmentById(id);

		// Display id to EditText
		edtEstabId.setText(estab.getId());

		// Display name to EditText
		edtEstabName.setText(estab.getName());

		// Display location to EditText
		edtLocation.setText(estab.getLocation());

		// Display date review
		date = estab.getDateReview();
		txtDate.setText(estab.getDateReview());

		// Display type of meal
		meal = estab.getTypeOfMeal();
		txtMeal.setText(estab.getTypeOfMeal());

		// Display cost
		if (estab.getCost() > 0) {
			cost = estab.getCost();
			txtCost.setText(Float.toString(estab.getCost()) + " US$");
		}

		// Display rate service
		serviceScore = estab.getRateService();
		rateService.setRating(estab.getRateService());

		// Display rate atmosphere
		atmosphereScore = estab.getRateAtmosphere();
		rateAtmosphere.setRating(estab.getRateAtmosphere());

		// Display rate food
		foodScore = estab.getRateFood();
		rateFood.setRating(estab.getRateFood());

		// Display rate overall
		overallScore = estab.getRateOverall();
		rateOverall.setRating(estab.getRateOverall());

		// Display rate comments
		if (estab.getComment() != null && !estab.getComment().isEmpty()) {
			edtComments.setText(estab.getComment());
		}
	}

	private void addDataToSpinnTypeOfEstab() {
		ArrayList<String> listTypeEstablishment = typeEstabDataSource
				.getAllTypeOfEstablishs();
		adapterForTypeOfEstab = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, listTypeEstablishment);
		adapterForTypeOfEstab
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinTypeOfEstab.setAdapter(adapterForTypeOfEstab);
		spinTypeOfEstab
				.setSelection((int) estab.getIdTypeOfEstablishment() - 1);
	}

	private void addDataToSpinnTypeOfFood() {
		ArrayList<String> listTypeFood = typeFoodDataSource.getAllTypeOfFood();
		adapterForTypeOfFood = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, listTypeFood);
		adapterForTypeOfFood
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinTypeOfFood.setAdapter(adapterForTypeOfFood);
		spinTypeOfFood.setSelection((int) estab.getIdTypeOfFood() - 1);
	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btnSave:
			// Check all required field
			if (!checkAllRequiredField())
				return;

			dialogWaiting = ProgressDialog.show(this, "Loading",
					"Updating Data");

			Thread th = new Thread(new Runnable() {
				public void run() {
					// Set new Name Establishment
					estab.setName(edtEstabName.getText().toString());
					// Set new Type of Establishment
					estab.setIdTypeOfEstablishment(typeEstabDataSource
							.getIdByName((String) spinTypeOfEstab
									.getSelectedItem()));
					// Set new Type of Food
					estab.setIdTypeOfFood(typeFoodDataSource
							.getIdByName((String) spinTypeOfFood
									.getSelectedItem()));
					// Set new Location
					estab.setLocation(edtLocation.getText().toString());
					// Set new Rate Service
					estab.setRateService(serviceScore);
					// Set new Rate Atmosphere
					estab.setRateAtmosphere(atmosphereScore);
					// Set new Rate Food
					estab.setRateFood(foodScore);
					// Set new Rate Overall
					estab.setRateOverall(overallScore);
					// Set new Date Review
					estab.setDateReview(date);
					// Set new Type of Meal
					estab.setTypeOfMeal(meal);
					// Set new Comments
					estab.setComment(edtComments.getText().toString());
					// Set new Cost
					estab.setCost(cost);

					// Update new data
					final boolean result = estabDataSource
							.updateEstablishment(estab);
					handler.post(new Runnable() {
						public void run() {
							if (result) {
								// Hide Button Save and Cancel
								Toast.makeText(EditEstablishActivity.this,
										"update successful", Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(EditEstablishActivity.this,
										"update unsuccessful",
										Toast.LENGTH_SHORT).show();
							}
							EditEstablishActivity.this.finish();
						}
					});
					
					// Close dialog
					dialogWaiting.dismiss();
				}
			});
			th.start();
			break;

		case R.id.btnCancel:
			this.finish();
			break;

		case R.id.layoutService:
			dialogRate.setTitle("Rate Service");
			ratingEstab.setRating(serviceScore);

			// submit rating
			Button btnSubmitService = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitService.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					serviceScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateService.setRating(serviceScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateService = (FrameLayout) findViewById(R.id.layoutService);
			layoutRateService.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutAtmosphere:
			dialogRate.setTitle("Rate Atmosphere");
			ratingEstab.setRating(atmosphereScore);

			// submit rating
			Button btnSubmitAtmosphere = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitAtmosphere.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					atmosphereScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateAtmosphere.setRating(atmosphereScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateAtmosphere = (FrameLayout) findViewById(R.id.layoutAtmosphere);
			layoutRateAtmosphere.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutFood:
			dialogRate.setTitle("Rate Food");
			ratingEstab.setRating(foodScore);

			// submit rating
			Button btnSubmitFood = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitFood.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					foodScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateFood.setRating(foodScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateFood = (FrameLayout) findViewById(R.id.layoutFood);
			layoutRateFood.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutOverall:
			dialogRate.setTitle("Rate Overall");
			ratingEstab.setRating(overallScore);

			// submit rating
			Button btnSubmitOverall = (Button) dialogRate
					.findViewById(R.id.btnSubmit);
			btnSubmitOverall.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					overallScore = ratingEstab.getRating();
					ratingEstab.setRating(0);
					rateOverall.setRating(overallScore);
					dialogRate.dismiss();
				}
			});

			// Hide error
			FrameLayout layoutRateOverall = (FrameLayout) findViewById(R.id.layoutOverall);
			layoutRateOverall.setBackgroundResource(R.drawable.border);

			dialogRate.show();
			break;

		case R.id.layoutTime:
			dialogTime.setTitle("Set Time");
			dialogTime.show();
			break;

		case R.id.layoutMeal:
			dialogMeal.setTitle("Meal Option                   ");
			dialogMeal.show();
			break;

		case R.id.layoutCost:
			dialogCost.setTitle("Set Cost");
			dialogCost.show();
			break;

		case R.id.btnNewTypeOfEstab:
			dialogNewTypeOfEstab.setTitle("New Type Of Establishment");
			dialogNewTypeOfEstab.show();
			break;

		case R.id.btnNewTypeOfFood:
			dialogNewTypeOfFood.setTitle("New Type Of Food");
			dialogNewTypeOfFood.show();
			break;
		default:
			break;
		}
	}

	private void addNewTypeOfEstabEvent() {
		Button btnNew = (Button) dialogNewTypeOfEstab.findViewById(R.id.btnNew);
		final EditText edtNew = (EditText) dialogNewTypeOfEstab
				.findViewById(R.id.edtNewType);

		btnNew.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				String typeOfEstab = edtNew.getText().toString();
				edtNew.setText("");
				if (!typeOfEstab.isEmpty()
						&& !typeEstabDataSource.checkNameExists(typeOfEstab)) {
					typeEstabDataSource.createTypeOfEstablishment(typeOfEstab);
					adapterForTypeOfEstab.add(typeOfEstab);
					spinTypeOfEstab.setSelection(adapterForTypeOfEstab
							.getPosition(typeOfEstab));
					dialogNewTypeOfEstab.dismiss();
				} else {
					dialogNewTypeOfEstab.dismiss();
				}
			}
		});
	}

	private void addNewTypeOfFoodEvent() {
		Button btnNew = (Button) dialogNewTypeOfFood.findViewById(R.id.btnNew);
		final EditText edtNew = (EditText) dialogNewTypeOfFood
				.findViewById(R.id.edtNewType);

		btnNew.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				String typeOfFood = edtNew.getText().toString();
				edtNew.setText("");
				if (!typeOfFood.isEmpty()
						&& !typeFoodDataSource.checkNameExists(typeOfFood)) {
					typeFoodDataSource.createTypeOfFood(typeOfFood);
					adapterForTypeOfFood.add(typeOfFood);
					spinTypeOfFood.setSelection(adapterForTypeOfFood
							.getPosition(typeOfFood));
					dialogNewTypeOfFood.dismiss();
				} else {
					dialogNewTypeOfFood.dismiss();
				}
			}
		});
	}

	private boolean checkAllRequiredField() {
		String nameEstab = edtEstabName.getText().toString();
		String error = "";
		if (serviceScore == 0 || atmosphereScore == 0 || foodScore == 0
				|| overallScore == 0 || nameEstab.isEmpty()) {
			if (nameEstab.isEmpty()) {
				EditText edtName = (EditText) findViewById(R.id.edtEstabName);
				edtName.setBackgroundResource(R.drawable.error);
				error = "Pleased enter name establishment & ";
			}

			if (serviceScore == 0) {
				FrameLayout layoutRateService = (FrameLayout) findViewById(R.id.layoutService);
				layoutRateService.setBackgroundResource(R.drawable.error);
			}

			if (atmosphereScore == 0) {
				FrameLayout layoutRateAtmosphere = (FrameLayout) findViewById(R.id.layoutAtmosphere);
				layoutRateAtmosphere.setBackgroundResource(R.drawable.error);
			}

			if (foodScore == 0) {
				FrameLayout layoutRateFood = (FrameLayout) findViewById(R.id.layoutFood);
				layoutRateFood.setBackgroundResource(R.drawable.error);
			}

			if (overallScore == 0) {
				FrameLayout layoutRateOverall = (FrameLayout) findViewById(R.id.layoutOverall);
				layoutRateOverall.setBackgroundResource(R.drawable.error);
			}

			// Notify to view
			Toast.makeText(this, error + "Pleased rate all", Toast.LENGTH_LONG)
					.show();
			return false;
		} else
			return true;
	}

	private void cancelDialogClicked() {
		// Cancel Rate
		Button btnCancelRate = (Button) dialogRate.findViewById(R.id.btnCancel);
		btnCancelRate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogRate.dismiss();
				ratingEstab.setRating(0);
			}
		});

		// Cancel Time
		Button btnCancelTime = (Button) dialogTime.findViewById(R.id.btnCancel);
		btnCancelTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogTime.dismiss();
			}
		});

		// Cancel Meal
		Button btnCancelMeal = (Button) dialogMeal.findViewById(R.id.btnCancel);
		btnCancelMeal.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogMeal.dismiss();
			}
		});

		// Cancel Cost
		Button btnCancelCost = (Button) dialogCost.findViewById(R.id.btnCancel);
		btnCancelCost.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogCost.dismiss();
			}
		});

		// Button Cancel Dialog New Type Of Estab
		Button btnCancelTypeEstab = (Button) dialogNewTypeOfEstab
				.findViewById(R.id.btnCancel);

		btnCancelTypeEstab.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogNewTypeOfEstab.dismiss();
			}
		});

		// Button Cancel Dialog New Type Of Food
		Button btnCancelTypeFood = (Button) dialogNewTypeOfFood
				.findViewById(R.id.btnCancel);

		btnCancelTypeFood.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogNewTypeOfFood.dismiss();
			}
		});
	}

	private void setTime() {
		Button btnSet = (Button) dialogTime.findViewById(R.id.btnSet);
		btnSet.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				DatePicker dateEstab = (DatePicker) dialogTime
						.findViewById(R.id.dateEstab);
				date = Integer.toString(dateEstab.getDayOfMonth()) + "/"
						+ Integer.toString(dateEstab.getMonth() + 1) + "/"
						+ Integer.toString(dateEstab.getYear());
				txtDate.setText(date);
				dialogTime.dismiss();
			}
		});
	}

	private void selectTypeOfMeal() {
		Button btnSelectMeal = (Button) dialogMeal.findViewById(R.id.btnSelect);
		btnSelectMeal.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				RadioGroup rg = (RadioGroup) dialogMeal
						.findViewById(R.id.rgMeal);
				RadioButton radioSelected = (RadioButton) dialogMeal
						.findViewById(rg.getCheckedRadioButtonId());
				meal = radioSelected.getText().toString();
				txtMeal.setText(meal);
				dialogMeal.dismiss();
			}
		});
	}

	private void setCost() {
		Button btnSetCost = (Button) dialogCost.findViewById(R.id.btnSet);
		btnSetCost.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				EditText edtCost = (EditText) dialogCost
						.findViewById(R.id.edtCost);
				if (!edtCost.getText().toString().isEmpty()) {
					txtCost.setText(edtCost.getText() + " US$");
					cost = Float.parseFloat(edtCost.getText().toString());
				} else {
					txtCost.setText(" US$");
					cost = 0;
				}

				dialogCost.dismiss();
			}
		});
	}

	@TargetApi(9)
	private void EventEditTextTextChanged() {

		// EditText id Filter
		InputFilter filter = new InputFilter() {
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {
				for (int i = start; i < end; i++) {
					if (!Character.isLetterOrDigit(source.charAt(i))) {
						return "";
					}
				}
				return null;
			}
		};

		// EditText Name Establishment
		edtEstabName.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				if (s.toString().isEmpty()) {
					Toast.makeText(EditEstablishActivity.this,
							"Please enter name establishment",
							Toast.LENGTH_LONG).show();
					edtEstabName.setBackgroundResource(R.drawable.error);
				} else {
					edtEstabName
							.setBackgroundResource(android.R.drawable.edit_text);
				}
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
		});

		// EditText name Filter
		edtEstabName.setFilters(new InputFilter[] { filter });
	}
}
